/**
 * @author 甜圆
 * @version v1.0.1
 * @date 2025/8/25 16:18
 * @package PACKAGE_NAME
 * @copyright 甜圆
 */
import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Client {
    private static Socket socket;
    private static BufferedReader in;
    private static PrintWriter out;
    private static boolean isRunning = true;

    public static void main(String[] args) {
        try {
            // 连接到服务器
            socket = new Socket("localhost", 8989);
            System.out.println("已连接到服务器");

            // 获取输入输出流
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            // 创建线程用于接收服务器消息
            Thread receiverThread = new Thread(new ServerMessageReceiver());
            receiverThread.start();

            // 读取用户输入并发送给服务器
            Scanner scanner = new Scanner(System.in);
            String userInput;

            while (isRunning) {
                System.out.print("请输入消息 (输入quit退出): ");
                userInput = scanner.nextLine();

                // 发送消息到服务器
                out.println(userInput);

                // 如果输入quit，关闭客户端
                if ("quit".equalsIgnoreCase(userInput)) {
                    isRunning = false;
                    break;
                }
            }

            // 关闭资源
            scanner.close();
            out.close();
            in.close();
            socket.close();
            System.out.println("客户端已关闭");

        } catch (IOException e) {
            if (!isRunning) {
                System.out.println("客户端已关闭");
            } else {
                System.out.println("连接错误: " + e.getMessage());
            }
        }
    }

    // 接收服务器消息的线程类
    static class ServerMessageReceiver implements Runnable {
        public void run() {
            try {
                String serverResponse;
                while (isRunning && (serverResponse = in.readLine()) != null) {
                    System.out.println("\n" + serverResponse);
                    System.out.print("请输入消息 (输入quit退出): ");

                    // 如果服务器返回的是关闭请求确认，客户端也准备关闭
                    if (serverResponse.contains("服务器已收到关闭请求")) {
                        isRunning = false;
                    }
                }
            } catch (IOException e) {
                if (isRunning) {
                    System.out.println("\n与服务器的连接已断开: " + e.getMessage());
                }
            }
        }
    }
}
